package com.yzh.openai.domain.weixin.service.message;

import com.yzh.openai.domain.weixin.model.entity.MessageTextEntity;
import com.yzh.openai.domain.weixin.model.entity.UserBehaviorMessageEntity;
import com.yzh.openai.domain.weixin.model.valobj.EventVO;
import com.yzh.openai.domain.weixin.model.valobj.MsgTypeVO;
import com.yzh.openai.domain.weixin.service.IWeiXinBehaviorService;
import com.yzh.openai.types.utils.xml.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

@Slf4j
public abstract class AbstractWeiXinBehaviorService implements IWeiXinBehaviorService {
    @Value("${wx.config.originalid}")
    protected String originalId;

    @Override
    public String acceptUserBehavior(UserBehaviorMessageEntity userBehaviorMessageEntity) {
        //首先判断微信发送过来的是事件消息还是普通消息
        String result = "";
        if (MsgTypeVO.EVENT.getCode().equals(userBehaviorMessageEntity.getMsgType())) {
            //关注公众号、落库用户信息
            if (EventVO.SUBSCRIBE.getCode().equals(userBehaviorMessageEntity.getEvent())) {
                result = insertUserAccount(userBehaviorMessageEntity);
            }
        }
        if (MsgTypeVO.TEXT.getCode().equals(userBehaviorMessageEntity.getMsgType())) {
            //判断是验证码还是问答消息
            if (userBehaviorMessageEntity.getContent().equals("666")) {
                result = createCode(userBehaviorMessageEntity);
            } else {
                result = QA(userBehaviorMessageEntity);
            }
        }
        return result;
    }

    protected abstract String insertUserAccount(UserBehaviorMessageEntity userBehaviorMessageEntity);

    protected abstract String createCode(UserBehaviorMessageEntity userBehaviorMessageEntity);

    protected abstract String QA(UserBehaviorMessageEntity userBehaviorMessageEntity);

    /**
     * 构建通用响应结果
     *
     * @param openid
     * @return
     */
    protected MessageTextEntity buildResponse(String openid) {
        MessageTextEntity response = new MessageTextEntity();
        response.setToUserName(openid);
        response.setFromUserName(originalId);
        response.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        response.setMsgType("text");
        return response;
    }

    /**
     * 构建返回结果
     *
     * @param response
     * @param content
     * @param openid
     * @return
     */
    protected String buildReturnResponse(MessageTextEntity response, String content, String openid) {
        response.setContent(content);
        String result = XmlUtil.beanToXml(response);
        return result;
    }
}
